package com.educate.member.rpc.provide.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.educate.common.utils.converter.ListUtils;
import com.educate.common.utils.exception.AppException;
import com.educate.common.web.BeanUtils;
import com.educate.member.dao.FamilyDao;
import com.educate.device.model.bo.FamilyBO;
import com.educate.device.model.po.Family;
import com.educate.member.rpc.api.FamilyService;
import lombok.extern.log4j.Log4j2;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

@Log4j2
@Service(
        version = "${api.service.version}",
        application = "${dubbo.application.id}",
        protocol = "${dubbo.protocol.id}",
        registry = "${dubbo.registry.id}"
)
public class FamilyServiceImpl implements FamilyService {

    @Resource FamilyDao familyDao;

    @Override
    public void create(FamilyBO bo) {
        familyDao.insert(bo);
    }

    @Override
    public void delete(FamilyBO bo) {
        familyDao.delete(bo);
    }

    @Override
    public void delete(String familyId) {
        familyDao.deleteById(familyId);
    }

    @Override
    public FamilyBO detail(String familyId) {
        Optional<Family> optional = familyDao.findById(familyId);
        if (!optional.isPresent()) {
            throw new AppException("不存在的实例");
        }
        return new FamilyBO(optional.get());
    }

    @Override
    public FamilyBO detail(FamilyBO bo) {
//        return detail(bo.getOrganizationId());
        return null;
    }

    @Override
    public void update(FamilyBO bo) {
        Optional<Family> optional = familyDao.findById(bo.getFamilyId());
        if (!optional.isPresent()) {
            throw new AppException("不存在的实例");
        }
        BeanUtils.copyPropertiesNonEmpty(bo, optional.get());
        familyDao.save(optional.get());
    }

    @Override
    public Page<FamilyBO> query(FamilyBO bo, PageRequest pageRequest) {
        return familyDao.query(bo, pageRequest).map(FamilyBO::new);
    }

    @Override
    public List<FamilyBO> list(FamilyBO bo) {
        List<Family> result = familyDao.findAll();
        return ListUtils.map(result, FamilyBO::new);
    }
}
